package org.zjvis.dlt;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.zjvis.dlt.data.vo.DatabaseRequest;
import org.zjvis.dlt.data.vo.SchemaRequest;
import org.zjvis.dlt.enums.ApiResultCode;
import org.zjvis.dlt.model.ApiResult;
import org.zjvis.dp.data.lineage.data.DatabaseConfig;
import org.zjvis.dp.data.lineage.parser.database.DatabaseFactory;

/**
 * @author zhouyu
 * @create 2023-07-06 11:18
 */
@Api(tags = "数据库访问接口")
@RestController
public class DatabaseController {

    @Resource
    DatabaseFactory databaseFactory;

    @PostMapping(value = "/connectTest")
    @ApiOperation(value = "测试数据库")
    public ApiResult<Void> connectTest(@RequestBody DatabaseRequest databaseRequest) {
        DatabaseConfig databaseConfig = new DatabaseConfig();
        BeanUtils.copyProperties(databaseRequest, databaseConfig);
        try {
            databaseFactory.createDatabaseService(databaseRequest.getSqlType()).connectionTest(databaseConfig);
            return ApiResult.valueOf(ApiResultCode.SUCCESS);
        } catch (Exception e) {
            return ApiResult.error(ApiResultCode.SYS_ERROR, e.getMessage());
        }
    }

    @PostMapping(value = "/getAllDatabase")
    @ApiOperation(value = "获取所有数据库名")
    public ApiResult<List<String>> getAllDatabase(@RequestBody DatabaseRequest databaseRequest) {
        DatabaseConfig databaseConfig = new DatabaseConfig();
        BeanUtils.copyProperties(databaseRequest, databaseConfig);
        List<String> databaseNameList =
                databaseFactory.createDatabaseService(databaseRequest.getSqlType()).getAllDatabase(databaseConfig);
        return ApiResult.valueOf(databaseNameList);
    }

    @PostMapping(value = "/getAllSchema")
    @ApiOperation(value = "获取所有数据模式名")
    public ApiResult<List<String>> getAllSchema(@RequestBody SchemaRequest schemaRequest) {
        DatabaseConfig databaseConfig = new DatabaseConfig();
        BeanUtils.copyProperties(schemaRequest, databaseConfig);
        List<String> schemaList = databaseFactory.createDatabaseService(schemaRequest.getSqlType()).
                getAllSchema(
                        databaseConfig,
                        schemaRequest.getDatabaseName()
                );
        return ApiResult.valueOf(schemaList);
    }
}